import React, { useState, useEffect, useRef } from "react";
import { Button, Form, Table, message, Tag, InputNumber, Typography, Popconfirm, Tooltip, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { TableColumnsType } from 'antd';
import { getScheme, getRouteFlag, placeRoute, placeNeedDetail, affirmByIds, getScheme2, mergeRoute } from "@/common/api"
import styles from './intelligent.module.scss';
import SendDetail from "./detail";


const Intelligent: React.FC = () => {
    const [form] = Form.useForm();
    const [loadings, setLoadings] = useState<boolean>(false);
    const [tableData, setTableData] = useState<any[]>([]);
    const [tableData2, setTableData2] = useState<any[]>([]);
    const timer = useRef<any>(null);
    useEffect(() => {
        getRouteFlag().then((res: any) => {
            if (res.success) {
                if (res.data) {
                    init()
                }
            }
        })
    }, []);
    const init = async () => {
        setLoading3(true)
        let res: any = await placeNeedDetail({ pageNum: 1, pageSize: 300 })
        setLoading3(false)
        if (res.success) {
            let arr = res.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData(arr)
        }
        setLoading2(true)
        let res2: any = await placeRoute({
            pageNum: 1,
            pageSize: 300,
        })
        setLoading2(false)
        if (res2.success) {
            let arr = res2.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData2(arr)
        }
    }




    //生成配送方案
    const onFinish = () => {
        getData()
        close()     //先关闭上一次定时任务
    };
    const getData = () => {
        const values = form.getFieldsValue();
        setLoadings(true)
        getScheme({ ...values }).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                message.success(res.message)
                start()
                timer.current = setInterval(() => {
                    start()
                }, 2000);
            } else {
                message.error(res.message)
            }
        })
    }
    const start = () => {   //开始轮询
        getRouteFlag().then((res: any) => {
            if (res.success) {
                if (res.data) {
                    close()
                    resultSerach()
                }
            }
        })
    }
    //未确认方案生成
    const noSure = () => {
        getData2()
        close()     //先关闭上一次定时任务
    }
    const getData2 = () => {
        const values = form.getFieldsValue();
        setLoadings(true)
        getScheme2({ ...values }).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                message.success(res.message)
                start()
                timer.current = setInterval(() => {
                    start()
                }, 2000);
            } else {
                message.error(res.message)
            }
        })
    }
    const close = () => {
        if (timer.current) {
            clearInterval(timer.current)
            timer.current = null
        }
    }


    //结果查询
    const resultSerach = async () => {
        setLoading3(true)
        const values = form.getFieldsValue();
        let res: any = await placeNeedDetail({ pageNum: 1, pageSize: 300, placeWay: values.placeWay })
        setLoading3(false)
        if (res.success) {
            let arr = res.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData(arr)
        }
        setLoading2(true)
        let res2: any = await placeRoute({
            pageNum: 1,
            pageSize: 300,
            placeWayList: res.data.records.map((i: any) => i.needPlace).join(',')
        })
        setLoading2(false)
        if (res2.success) {
            let arr = res2.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData2(arr)
        }
    }


    const getTop = () => {
        return <Form
            layout="inline"
            form={form}
            onFinish={onFinish}
            autoComplete="off"
            initialValues={{ dynamicDisplay: 4.6 }}
        >
            <Form.Item name="dynamicDisplay" label="配送总重(吨):" style={{ marginBottom: '10px' }} rules={[{ required: true, message: '请输入配送总重' }]}>
                <InputNumber placeholder="请输入" min={0} max={4.6} />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" htmlType="submit" loading={loadings}>生成配送方案</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" onClick={noSure} loading={loadings}>未确认方案生成</Button>
            </Form.Item>

            <Form.Item name="placeWay" label="配送地点:" style={{ marginBottom: '10px' }}>
                <Input placeholder="请输入配送地点" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" onClick={resultSerach} loading={loadings} >结果查询</Button>
            </Form.Item>
        </Form>
    }





    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '配送地点',
            dataIndex: 'needPlace',
            onCell: (record) => ({
                onClick: () => getItem(record),
                style: {
                    color: record.id === item.id ? 'red' : '',
                    cursor: 'pointer',
                },
            }),
            render: (text) => <span>{text}</span>,
        },
        {
            title: '需求重量(吨)',
            dataIndex: 'needLoad',
            //  width: 100,
        },
        {
            title: '剩余重量(吨)',
            dataIndex: 'leftRequire',
            // width: 120,
        },
        {
            title: '配送方案',
            dataIndex: 'distributionPlan',

        },
        {
            title: '拼车点',
            dataIndex: 'carDot',
            render: (text, record) => {
                const tooltipContent = record.carDotSet ? record.carDotSet.join(',') : '暂无'
                return (
                    <Tooltip title={tooltipContent} placement="top">
                        <span>{text || '-'}</span>
                    </Tooltip>
                );
            },
            width: 120,

        },
        {
            title: '路线确认结果',
            dataIndex: 'confirmedStr', // 仅用于显示
            filters: [
                { text: '未确认', value: 0 },
                { text: '全部确认', value: 1 },
            ],
            onFilter: (value, record) => {
                return record.allConfirmedFlag === value;
            },
            render: (text, record) => (
                <span style={{ color: record.allConfirmedFlag === 1 ? '#3B77FF' : '' }}>
                    {text}
                </span>
            ),
        },
    ];
    const columns2: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '路线',
            dataIndex: 'placeWay',
            // width: 100,
        },
        {
            title: '类型',
            dataIndex: 'markType',
            minWidth: 100,
            render: (text) => {
                let color = '';
                if (text == '拼车') {
                    color = '#7BAD8D';
                } else if (text == '整车') {
                    color = '#758DD1';
                }
                else if (text == '待拼车') {
                    color = '#F7B707';
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '配载(吨)',
            dataIndex: 'stowage',
            minWidth: 100,
        },
        {
            title: '总重(吨)',
            dataIndex: 'totalLoad',
            minWidth: 100,
        },
        {
            title: '总距离(km)',
            dataIndex: 'totalDistance',
            minWidth: 120,
        },
        {
            title: '可补偿量',
            dataIndex: 'monthPlanFills',
            minWidth: 100,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            width: 220,
            render: (_: any, record) => {
                return <>
                    <Typography.Link onClick={() => detail(record, 2)} style={{ marginRight: 16 }}>
                        详情
                    </Typography.Link>

                    {record.affirmFlag == 0 && <Popconfirm
                        title="是否确认当前路线？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => lineSure(record)}
                    >
                        <Typography.Link style={{ color: '#1677FF', marginRight: 16 }}>路线确认</Typography.Link>
                    </Popconfirm>}

                    {item.id && tableData2.length > 1 && <Typography.Link onClick={() => detail(record, 3)} >
                        合并路线
                    </Typography.Link>
                    }
                </>

            },
        },

    ];

    const [loading2, setLoading2] = useState(false)  //配送方案
    const [loading3, setLoading3] = useState(false) //配送需求
    const [item, setItem] = useState<any>({})  //选中的配送需求
    const [item2, setItem2] = useState<any>({})  //选中的配送方案
    const [data, setData] = useState<any>(null)





    //触发筛选等操作
    const handleTableChange = async (_: any, filters: any) => {
        let data = []   //筛选后的数据
        const confirmedValues = filters.confirmedStr;
        if (confirmedValues && confirmedValues.length == 1) {
            data = tableData.filter((i) => i.allConfirmedFlag == confirmedValues[0])
        } else {
            data = tableData
        }
        if (data.length == 0) {
            setTableData2([])
            return
        }

        setLoading2(true)
        let res: any = await placeRoute({
            pageNum: 1,
            pageSize: 300,
            placeWayList: data.map((i: any) => i.needPlace).join(',')
        })
        setLoading2(false)
        if (res.success) {
            let arr = res.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData2(arr)
        }
    };
    //点击配送地点
    const getItem = (record: any) => {
        setLoading2(true)
        setItem({ ...record })
        placeRoute({ pageNum: 1, pageSize: 300, placeWay: record.needPlace }).then((res: any) => {
            setLoading2(false)
            if (res.success) {
                let arr = res.data.records.map((i: any, index: number) => {
                    return {
                        ...i,
                        key: index, // 简单地用索引作为 key
                    }
                })
                setTableData2(arr)
            }
        })
    }

    //详情
    const detail = (record: any, e: Number) => {  //1--配送需求，2--配送方案  3--路线合并
        if (e == 1) {
            setData({ ...record, type: e })
        }
        if (e == 2) {
            setData({ data: [...record.detailList], type: e })
        }
        if (e == 3) {
            setItem2(record)
            setData({ data: tableData2.filter((i) => i.id != record.id), type: e })
        }
    }
    //路线确认
    const lineSure = (record: any) => {
        affirmByIds({ ids: record.id }).then((res: any) => {
            if (res.success) {
                message.success(res.message)
                excute()
            } else {
                message.error(res.message)
            }
        })
    }
    //合并路线
    const merge = async (selectedRowKey: any) => {
        let param = {
            splitRouteId: item2.id,
            addRouteId: selectedRowKey,
            needPlace: item.needPlace
        }
        let res: any = await mergeRoute(param)
        if (res.success) {
            message.success(res.message)
            excute()
        } else {
            message.error(res.message)
        }
    }
    //路线确认及合并路线后的操作，刷新两张列表
    const excute = async () => {
        setLoading3(true)
        const values = form.getFieldsValue();
        let res: any = await placeNeedDetail({ pageNum: 1, pageSize: 300, placeWay: values.placeWay })
        setLoading3(false)
        if (res.success) {
            let arr = res.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index,
                }
            })
            setTableData(arr)
        }

        setLoading2(true)
        let res2: any = await placeRoute({ pageNum: 1, pageSize: 300, placeWay: item.needPlace })
        setLoading2(false)
        if (res2.success) {
            let arr = res2.data.records.map((i: any, index: number) => {
                return {
                    ...i,
                    key: index, // 简单地用索引作为 key
                }
            })
            setTableData2(arr)
        }


    }





    const getTable = () => {
        return <div style={{ display: 'flex', flexDirection: 'column', height: '100%', gap: '10px' }}>
            <div>配送需求</div>
            <Table
                bordered={true}
                columns={columns}
                dataSource={tableData}
                scroll={{ x: 'max-content' }}
                pagination={false}
                sticky={true}
                style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', width: '100%' }}
                loading={loading3}
                onChange={handleTableChange}

            />
            <div>配送方案</div>
            <Table
                bordered={true}
                columns={columns2}
                dataSource={tableData2}
                scroll={{ x: 'max-content' }}
                pagination={false}
                sticky={true}
                tableLayout="auto"
                style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', width: '100%' }}
                loading={loading2}
            />

            <SendDetail data={data} merge={merge} freshList={freshList} />
        </div>

    }

    const freshList = () => {
        excute()
    }


    return <>
        <div className={styles.all}>
            <div className={styles.top}>
                <div className={styles.search}>
                    {getTop()}
                </div>
            </div>
            <div className={styles.table}>
                <div className={styles.tablet}>
                    {getTable()}
                </div>
            </div>
        </div>

    </>
}


export default Intelligent
